module repository.GroupUserRepository;

import bootstrap.DatabaseBootstrap;
import hunt.framework;
import hunt.logging;
import std.conv : to;
import model;
import message.MsgDefine;
import core.stdc.time;

class GroupUserRepository : EntityRepository!( GroupUser , int){

  this()
  {
    super(defaultEntityManager());
  }

  this(EntityManager manager)
  {
    super(manager);
  }

  void addGroupUser(string userId,int groupId,string nickname,EntityManager em)
  {
    //scope(exit)
    //{
    //  _manager.close();
    //}
    auto insert = em.createQuery!(GroupUser)("INSERT INTO GroupUser u(u.groupId,u.userId,u.nickname,u.since) VALUES (:groupId,:userId,:nickname,:since)");
    insert.setParameter("groupId",groupId);
    insert.setParameter("userId",userId);
    insert.setParameter("nickname",nickname);
    insert.setParameter("since",core.stdc.time.time(null));
    insert.exec();
  }

  uint selectManager(string groupId )
  {
    scope(exit)
    {
      _manager.close();
    }
    auto  query = _manager.createQuery!(GroupUser)(" select * from GroupUser a where a.groupId = :groupId  ORDER BY a.since LIMIT 2").
    setParameter("groupId", to!uint(groupId));
    GroupUser[] objs = query.getResultList();
    if (objs.length >= 2)
    {
        return objs[1].userId;
    }
    else
    {
        return 0;
    }
  }


  bool isExist(uint uid, uint groupId)
  {
      GroupUser user =  find(new Condition("%s = %s and %s = %s" , Field.groupId , groupId , Field.userId , uid));
      return user !is null ? true : false;
  }

  GroupUser[] findAllByID(int groupId)
  {
    scope(exit)
    {
      _manager.close();
    }
    auto  query = _manager.createQuery!(GroupUser)(" select * from GroupUser a where a.groupId = :groupId  ORDER BY a.since").
    setParameter("groupId", to!uint(groupId));
    return query.getResultList();
  }

  GroupUser[] findAllByUserId(uint userId)
  {
    return findAll(new Condition("%s = %s" , Field.userId , userId));
  }

  void deleteGroupUser(string groupId, string userId,EntityManager em)
  {
    auto update = em.createQuery!(GroupUser)("DELETE FROM GroupUser u WHERE u.userId = :userId AND u.groupId = :groupId");
    update.setParameter("userId",userId);
    update.setParameter("groupId",groupId);
    try{
      update.exec();
    }
    catch(Exception e)
    {
      logError("deleteGroupUser error : %s",e.msg);
    }
  }

  void deleteAllGroupUser(string groupId)
  {
    scope(exit)
    {
      _manager.close();
    }

    auto update = _manager.createQuery!(GroupUser)("DELETE FROM GroupUser u WHERE u.groupId = :groupId");
    update.setParameter("groupId",groupId);
    try{
      update.exec();
    }
    catch(Exception e)
    {
      logError("deleteAllGroupUser error : %s",e.msg);
    }
  }
}

